<template>
  <div class="dropdown_custom">
    <div @click="open">
      <span class="text">{{ showTitle }}</span>
      <van-icon class="icon" name="arrow-down" color="#C8C8C8" />
    </div>

    <van-popup v-model="show" round position="bottom">
      <van-cascader
        v-model="cascaderValue"
        :title="popupTitle"
        :options="popupOptions"
        :field-names="fieldNames"
        @close="close"
        @finish="onFinish"
      />
    </van-popup>
  </div>
</template>

<script>
export default {
  props: {
    title: {
      type: String,
      default: ''
    },
    popupTitle: {
      type: String,
      default: '请选择'
    },
    popupOptions: {
      type: Array,
      default () {
        return [];
      }
    },
    fieldNames: {
      type: Object,
      default() {
        return {
          text: 'text',
          value: 'value',
          children: 'children'
        };
      }
    }
  },
  data () {
    return {
      show: false,
      fieldValue: '',
      cascaderValue: ''
    };
  },
  computed: {
    showTitle() {
      if (this.fieldValue) {
        return this.fieldValue;
      } else {
        return this.title ? this.title : '请选择';
      }
    }
  },
  methods: {
    open () {
      this.show = true;
    },
    close () {
      this.show = false;
    },
    resetFieldValue () {
      this.fieldValue = '';
      this.cascaderValue = '';
    },
    // 全部选项选择完毕后，会触发 finish 事件
    onFinish({ selectedOptions }) {
      this.close();
      const _key = this.fieldNames.text;
      this.fieldValue = selectedOptions.map((option) => option[_key]).join('/');
      this.$emit('onFinish', selectedOptions);
    }
  }
};
</script>

<style>
  .dropdown_custom .van-cascader__options {
    height: 200px;
  }
</style>

<style lang="scss" scoped>
  .dropdown_custom {
    font-size: 13px;
    .text {
      display: inline-block;
      max-width: 60px;
      color: #666;
      margin-right: 5px;
      vertical-align: middle;
      text-overflow: ellipsis;
      overflow: hidden;
      white-space: nowrap;
    }
    .icon {
      vertical-align: middle;
    }
  }
</style>
